package com.example.cdctest.controller;
import com.example.cdctest.pojo.Config;
import com.example.cdctest.pojo.Knowledge;
import com.example.cdctest.pojo.Notice;
import com.example.cdctest.pojo.UserInfo;
import com.example.cdctest.service.KnowledgeCollectionService;
import com.example.cdctest.service.KnowledgeService;
import com.example.cdctest.service.NoticeService;
import com.example.cdctest.util.JSONResult;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/services")
public class KnowledgeController {
    @Resource
    private KnowledgeService knowledgeService;
    @Resource
    private KnowledgeCollectionService knowledgeCollectionService;
    @Resource
    private NoticeService noticeService;
    @RequestMapping("list")
    public ModelAndView list(Integer pageNum, HttpServletRequest request,String content){
        ModelAndView modelAndView=new ModelAndView();
        if(pageNum==null){
            pageNum=1;
        };
        Integer pageSize=5;
        ServletContext servletContext=request.getSession().getServletContext();
        List<Config> configList=(List<Config>) servletContext.getAttribute("configs");
        for (Config config : configList) {
            if("web_knowledge_count".equals(config.getKey())){
                pageSize=Integer.parseInt(config.getValue());
            }
        }
        PageInfo<Knowledge> pageInfo=knowledgeService.getAllKnowledge(pageNum,pageSize,content);
        modelAndView.addObject("allKnowledge",pageInfo);
        modelAndView.setViewName("/services/list");
        return modelAndView;
    }
    @RequestMapping("knowledge")
    public ModelAndView getKnowledgeById(String id, HttpSession session){
        int knowledgeId=Integer.parseInt(id);
        Boolean isCollection=false;
        UserInfo loginUser=(UserInfo) session.getAttribute("loginUser");
        if (loginUser != null) {
            isCollection=knowledgeCollectionService.isCollection(loginUser.getId(),knowledgeId);
        }
        Knowledge knowledge = knowledgeService.getKnowledgeById(knowledgeId);
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.addObject("knowledge",knowledge);
        modelAndView.addObject("isCollection",isCollection);
        modelAndView.setViewName("/services/forum-post-view");
        return modelAndView;
    }

}
